package ace.module.account.core.impl.service.member.impl;

import ace.cmp.core.model.PageResultDto;
import ace.module.account.api.model.dto.IamAccountPassportDto;
import ace.module.account.api.model.input.AppOutInfoInput;
import ace.module.account.api.model.input.passport.IamAccountPassportFilterInput;
import ace.module.account.api.model.input.passport.IamAccountPassportRemoveInput;
import ace.module.account.api.model.input.passport.IamAccountPassportSearchOutInput;
import ace.module.account.core.impl.dao.entity.IamApplication;
import ace.module.account.core.impl.manager.IamAccountPassportManager;
import ace.module.account.core.impl.manager.IamApplicationManager;
import ace.module.account.core.impl.service.IamAccountPassportService;
import ace.module.account.core.impl.service.member.MemberPassportService;
import ace.module.common.api.constant.SystemRoleConstants;
import ace.module.common.api.model.input.PageInput;
import ace.module.common.api.model.input.TenantInput;
import ace.module.common.api.model.input.TenantPageInput;
import java.util.Collections;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 会员通行证服务.
 *
 * @author Caspar
 */
@AllArgsConstructor
@Component
public class MemberPassportServiceImpl implements MemberPassportService {

  private final IamAccountPassportService iamAccountPassportService;
  private final IamAccountPassportManager iamAccountPassportManager;
  private final IamApplicationManager iamApplicationManager;

  @Override
  public PageResultDto<IamAccountPassportDto> adminSearch(
      TenantPageInput<IamAccountPassportFilterInput> input) {
    AppOutInfoInput appOutInfoInput = AppOutInfoInput.of(
        SystemRoleConstants.MEMBER,
        input.getTenantId()
    );
    PageInput<IamAccountPassportSearchOutInput> pageInput = PageInput.<IamAccountPassportSearchOutInput>builder()
        .page(input.getPage())
        .data(IamAccountPassportSearchOutInput.builder()
            .outInfo(appOutInfoInput)
            .filter(input.getData())
            .build()
        )
        .build();

    return iamAccountPassportService.search(pageInput).check();
  }

  @Override
  public void adminRemove(TenantInput<IamAccountPassportRemoveInput> input) {
    IamApplication iamApplication = iamApplicationManager.getAndCheckByOutTypeAndOutId(SystemRoleConstants.MEMBER, input.getTenantId().toString());
    iamAccountPassportManager.removeLogicByAppIdIdAndIdIn(iamApplication.getId(), Collections.singletonList(input.getData().getId()));
  }
}